//
//  MCPickerImageHelper.swift
//  Alamofire
//
//  Created by MC on 2018/12/10.
//

import Foundation
import UIKit
import MobileCoreServices
import Photos


public class MCPickerImageHelper: NSObject {
    
    /// 选择图片的回调
    private var selectedImageBlock : ((UIImage) -> ())?
    
    private var allowsEditing : Bool = false
    
    
    private static let helper = MCPickerImageHelper()
    
    
    
    
    /// 打开系统相机
    /// - Parameter target: 控制器用来做present跳转
    /// - Parameter allowsEditing: 是否支持系统的编辑
    /// - Parameter completeHandler: 回调返回一个image对象
    public static func mc_openCamera(_ target: UIViewController ,allowsEditing: Bool = false, completeHandler:((UIImage)->())?) {
        helper.allowsEditing = allowsEditing
        helper.selectedImageBlock = completeHandler
        helper.openCamera(target, allowsEditing: allowsEditing)
    }
    
    
    /// 打开系统的相册
    /// - Parameter target: 控制器用来做present跳转
    /// - Parameter completeHandler: 是否支持系统的编辑
    public static func mc_openLibrary(_ target:UIViewController, completeHandler:((UIImage)->())?) {
        helper.allowsEditing = false
        helper.selectedImageBlock = completeHandler
        helper.openPhotoLibrary(target)
    }
        
    /// 打开自定义的相册
    ///
    /// - Parameters:
    ///   - target: 目标控制器，用来做页面跳转
    ///   - mediaType: 资源类型
    ///   - maxSelectCount: 最大选择图片数量
    ///   - completeHandler: 回调，图片数组
    public static func mc_openCustomLibrary(target: UIViewController, mediaType: MCAssetMediaType = .image,  maxSelectCount: Int = Int.max, completeHandler:((_ assets:[PHAsset])->())?) {

        helper.allowsEditing = false
        helper.openCustomLibrary(target: target, mediaType: mediaType, maxSelectCount: maxSelectCount, completeHandler: completeHandler)
    }
}





extension MCPickerImageHelper {
    /**
     * 打开相机拍照
     * allowsEditing 是否允许编辑
     */
    private func openCamera(_ target:UIViewController ,allowsEditing : Bool = false) {
        
        self.allowsEditing = allowsEditing
        
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.modalPresentationStyle = .fullScreen
            picker.sourceType = .camera
            picker.delegate = self
            picker.allowsEditing = allowsEditing
            target.present(picker, animated: true, completion: nil)
        } else {
            print("模拟其中无法打开照相机,请在真机中使用");
        }
    }
    
    /**
     * 打开相册，选照片
     * allowsEditing 是否允许编辑
     */
    private func openPhotoLibrary(_ target:UIViewController) {
        self.allowsEditing = false
        // 是否支持相册
        if UIImagePickerController.isValidImagePickerType(type: UIImagePickerType.UIImagePickerTypePhotoLibrary){
            let picker = UIImagePickerController()
            picker.modalPresentationStyle = .fullScreen
            picker.sourceType = .photoLibrary
            picker.delegate = self
            /// 选择资源类型
//            picker.mediaTypes = ["public.movie", "public.image"]
            target.present(picker, animated: true, completion: nil)
        } else {
            print("读取相册失败")
        }
    }
    
    
    private func openCustomLibrary(target: UIViewController, mediaType: MCAssetMediaType, maxSelectCount: Int = Int.max, completeHandler:((_ assets:[PHAsset])->())?) {
        self.allowsEditing = false

        let vc = MCPhotoLibraryListViewController()
        vc.maxSelected = maxSelectCount
        vc.completeHandler = completeHandler
        vc.mediaType = mediaType
        let nav = UINavigationController.init(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        target.present(nav, animated: true, completion: nil)
    }

}


extension MCPickerImageHelper: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
 
    /*
     指定用户选择的媒体类型 UIImagePickerControllerMediaType
     原始图片 UIImagePickerControllerOriginalImage
     修改后的图片 UIImagePickerControllerEditedImage
     裁剪尺寸 UIImagePickerControllerCropRect
     媒体的URL UIImagePickerControllerMediaURL
     原件的URL UIImagePickerControllerReferenceURL
     当来数据来源是照相机的时候这个值才有效 UIImagePickerControllerMediaMetadata
     */
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        
        
        let mediaType = info[UIImagePickerController.InfoKey.mediaType] as! String
        
        if mediaType == String(kUTTypeImage) {
            
            let originalImage : UIImage? = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
            let eidtImage : UIImage? = info[UIImagePickerController.InfoKey.editedImage] as? UIImage

            
            
//            let rect = info[UIImagePickerController.InfoKey.cropRect] as? CGRect ?? CGRect.init()
            
            let pickedImage = self.allowsEditing ? eidtImage : originalImage
            
            if let tempImage = pickedImage {
                            // 是否支持相册
                if UIImagePickerController.isValidImagePickerType(type: UIImagePickerType.UIImagePickerTypePhotoLibrary) {
                    // 相册
                } else if (UIImagePickerController.isValidImagePickerType(type: UIImagePickerType.UIImagePickerTypeCamera)){
                    // 相机
                    // 图片保存到相册
                    UIImageWriteToSavedPhotosAlbum(tempImage, self, Selector(("imageSave:error:contextInfo:")), nil)
                }
                
                if self.selectedImageBlock != nil {
                    self.selectedImageBlock!(tempImage)
                }
            }
            
            

            picker.dismiss(animated: true) { }
            
        }
    }
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}




extension PHAsset {
    
    /// PHAsset转图片
    public func toImage(mode: PHImageRequestOptionsDeliveryMode = .highQualityFormat) -> UIImage {
        
        var image = UIImage()
        
        // 新建一个默认类型的图像管理器imageManager
        let imageManager = PHImageManager.default()
        
        // 新建一个PHImageRequestOptions对象
        let imageRequestOption = PHImageRequestOptions()
        
        // PHImageRequestOptions是否有效
        imageRequestOption.isSynchronous = true
        
        // 缩略图的压缩模式设置为无
        imageRequestOption.resizeMode = .none
        
        // 缩略图的质量为高质量，不管加载时间花多少
        imageRequestOption.deliveryMode = mode
        
        // 按照PHImageRequestOptions指定的规则取出图片
        imageManager.requestImage(for: self, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: imageRequestOption, resultHandler: { (result, _) -> Void in
            image = result!
        })
        return image
    }
    
    
    public func toAVURLAsset(resultHandler: @escaping (AVURLAsset) -> Void) {
        
        /**
         获取视频的路径和时间
         urlAsset.url
         urlAsset.duration
         */
        
        
        let option = PHVideoRequestOptions()
        option.version = .current
        option.deliveryMode = .automatic
        option.isNetworkAccessAllowed = true
        
        let manager = PHImageManager.default()
        manager.requestAVAsset(forVideo: self, options: option) { (avasset, audioMix, array) in
            
            if let urlAsset: AVURLAsset = avasset as? AVURLAsset {
                resultHandler(urlAsset)
            }
        }
    }
}

extension String {
    /// 获取视频封面
    public func getVideoThumbnail(seconds: Double) -> UIImage? {
        
        let url = self
        if url.isEmpty {
            //默认封面图
            return UIImage.mc_placeholder_1x1
        }
        let aset = AVURLAsset(url: URL(fileURLWithPath: url), options: nil)
        let assetImg = AVAssetImageGenerator(asset: aset)
        assetImg.appliesPreferredTrackTransform = true
        assetImg.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
        do{
            let ctTime = CMTime.init(seconds: seconds, preferredTimescale: 60)
            let cgimgref = try assetImg.copyCGImage(at: ctTime, actualTime: nil)
            return UIImage(cgImage: cgimgref)
        }catch{
            return UIImage.mc_placeholder_1x1
        }
    }
    
    /// 获取视频的大小
    public func getVideoSize() -> UInt64 {        
        
        var path = self
        
        if path.contains("file://") {
            path = path.replacingOccurrences(of: "file://", with: "")
        }
        
        let filemanager = FileManager.init()
        
        if filemanager.fileExists(atPath: path) {
            
            do {
                let attributes = try filemanager.attributesOfItem(atPath: path)
                let size = attributes[FileAttributeKey.size] as! UInt64
                
                return size
            } catch {
                return 0
            }
        } else {
            return 0
        }
    }
}



extension Double {
    
    /// 获取视频时长
    public func toMinutesAndSeconds() -> String {

        let minutes = floor(self/60)
        
        let temp = self - minutes*60
        let seconds = Darwin.round(temp)
        
        var minutesStr = Int(minutes).stringValue
        if minutesStr.count <= 1 {
             minutesStr = "0" + minutesStr
        }
        
        var secondsStr = Int(seconds).stringValue
        
        if secondsStr.count <= 1 {
             secondsStr = "0" + secondsStr
        }

        return minutesStr + ":" + secondsStr
    }
}
